package check

import (
	"cost_api/internal/config"
	"cost_api/utils/iface"
	"regexp"
	"strings"
)

type costCodeValid struct {
	result  bool
	regexps config.Regexps
	regex   *regexp.Regexp
}

func NewCostCodeValid() iface.ICodeValid {
	return &costCodeValid{result: true}
}

func (c *costCodeValid) DefineRegexp(regexps ...string) iface.ICodeValid {
	//TODO implement me
	c.regexps = regexps
	return c
}

func (c *costCodeValid) relationRegexp(length int) bool {
	var reg string
	if (length < 0 || length > 10) || c.regexps == nil {
		return false
	}
	handle := func(str *strings.Builder, val string) {
		str.WriteString(val)
	}
	switch length {
	case 2:
		reg = c.regexps.GetSerial(1, handle)
	case 4:
		reg = c.regexps.GetSerial(2, handle)
	case 6:
		reg = c.regexps.GetSerial(3, handle)
	case 8:
		reg = c.regexps.GetSerial(4, handle)
	default:
		return false
	}
	c.regex, _ = regexp.Compile(reg)
	return true
}

func (c *costCodeValid) CheckCode(code string) iface.ICodeValid {
	//TODO implement me
	if !c.result {
		return c
	}
	if c.result = c.relationRegexp(len(code)); !c.result {
		return c
	}
	if len(code) > 8 {
		code = code[:9]
	}
	if !c.regex.MatchString(code) {
		c.result = false
	}
	return c
}

func (c *costCodeValid) GetParentCode(code string) string {
	return code[:len(code)-1]
}

func (c *costCodeValid) Check() bool {
	return c.result
}
